package Wizard.ImageLoad;

import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ImageView;

public class AsyncImageLoader {

	 private HashMap<String, SoftReference<Bitmap>> imageCache;
	  
	     public AsyncImageLoader() {
	    	 imageCache = new HashMap<String, SoftReference<Bitmap>>();
	     }
	  
	     public Bitmap loadDrawable(final String imageUrl, final CallbackImpl imageCallback,final String ImageID) {
	    	 System.out.println("(((((((+++++"+imageCache.containsKey(imageUrl));
	    	 if (imageCache.containsKey(imageUrl)) {
	             SoftReference<Bitmap> softReference = imageCache.get(imageUrl);
	             Bitmap bitmap = softReference.get();
	             if (bitmap != null) {
	                 return bitmap;
	             }
	         }
	         final Handler handler = new Handler() {
	             public void handleMessage(Message message) {
	            	 switch (message.what) {
	            	 case 100:
	                 imageCallback.imageLoaded((Bitmap) message.obj);
	                 break;
	            	 }
	             }
	         };
	         new Thread() {
	             @Override
	             public void run() {
	            	 Bitmap bitmap = loadImageFromUrl(imageUrl,ImageID);
	                 imageCache.put(imageUrl, new SoftReference<Bitmap>(bitmap));
	                 Message message = handler.obtainMessage(0, bitmap);
	                 handler.sendMessage(message);
	             }
	         }.start();
	         return null;
	     }
		public  Bitmap loadImageFromUrl(String url,String imageID) {
			URL m;
			InputStream i = null;
			try {
				m = new URL(url);
				i = (InputStream) m.getContent();
			} catch (MalformedURLException e1) {
				e1.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			//Drawable d = Drawable.createFromStream(i, "src");
			Bitmap bitmaps = BitmapFactory.decodeStream(i);
			System.out.println("Bitmap++++"+bitmaps);
		//	localSaveBitmap.getInstance().saveBmpToSd(bitmaps,imageID);
		
			return bitmaps;
		}
	  
		public interface ImageCallback{
			public void imageLoaded(Bitmap imageDrawable);
			
		}

		

}
